<?php
/**
* pipahr 
* modified based own owncloud sharing module to support sub accounts 
*/
require_once(OC_App::getAppPath('company') . "/lib/subaccounts.php");
require_once(OC_App::getAppPath('resumes') . "/lib/share/share.php");
require_once(OC_App::getAppPath('resumes') . "/lib/resume.php");

$LoginStats = PUtil::checkUserLogin(true);
if ($LoginStats !== true) {
   echo $LoginStats;
   exit();
}

OCP\JSON::callCheck();

if (isset($_POST['action']) && isset($_POST['itemType']) && isset($_POST['itemSource'])) {
   switch ($_POST['action']) {
      case 'share':
         if (isset($_POST['shareType']) && isset($_POST['shareWith']) && isset($_POST['permissions'])) {
            try {
               $itemType = JRequest::getString('itemType', '');
               $itemSource = JRequest::getInt('itemSource', 0); 
               $shareType = JRequest::getInt('shareType', 0);
               $shareWith = JRequest::getString('shareWith', '');
               $permissions  = ResumeShare::pickPermissions(JRequest::getInt('permissions', 0));
               $useToken = JRequest::getInt('setting', 0);
               $expiration = JRequest::getString('expiration', ''); 
               $shareWords = JRequest::getString('shareWords', '');

               if($shareType === OCP\Share::SHARE_TYPE_LINK && $shareWith == '') {
                     $shareWith = null;
               }

               // check share permission 
               $maxpermissions = ResumeShare::getMaxPermissions($itemSource); 
               if(!($maxpermissions & OCP\PERMISSION_SHARE)) {
                  OC_JSON::error(array('data' => array('message' => "您无权访问该资源")));
                  exit;
               }
               $emailArr = array_filter(explode(',', str_replace(' ', '', $shareWith)));
               if($shareType === OCP\Share::SHARE_TYPE_EMAIL) {
                  for($i=0;$i<count($emailArr);$i++){ 
                     if(!JMailHelper::isEmailAddress($emailArr[$i])) {
                        OC_JSON::error(array('data' => array('message' => "不合法的邮箱")));
                        exit;
                     }                     
                  }
                  $shareType = OCP\Share::SHARE_TYPE_LINK; 
               }
               else {
                  // check if shareWith is subaccount/group when shareType is not LINK alike  
                  $model = new PCompanyModelSubAccounts; 
                  if(($shareType === OCP\Share::SHARE_TYPE_USER && !$model->hasUser($shareWith)) || 
                     ($shareType === OCP\Share::SHARE_TYPE_GROUP && !$model->hasGroup($shareWith))) {
                     OC_JSON::error(array('data' => array('message' => "不合法的子账号或分组")));
                     exit;
                  }
               }

               $token = '';
               $notsharedlist = '';
               if(!empty($shareWith)){
                  $sharedlist = ResumeShare::getShareWithList($itemSource, $emailArr);
                  $sharedlist = empty($sharedlist)?array():$sharedlist;
                  $notsharedlist = array_values(array_unique(array_diff($emailArr, $sharedlist)));
                  $me = PFactory::getUser();
                  if((in_array($me->email, $notsharedlist) !== FALSE) || (in_array($me->username, $notsharedlist) !== FALSE)) {
                     OC_JSON::error(array('data' => array('message' => "你不能分享简历给自己")));
                     exit;
                  }
                  if(is_array($notsharedlist)){
                     foreach ($notsharedlist as $email) {
                        $token = OCP\Share::shareItem(
                           $itemType,
                           $itemSource,
                           $shareType,
                           $email,
                           ($permissions & $maxpermissions)
                        );
                     }
                  }
               }else{
                  $token = OCP\Share::shareItem(
                     $itemType,
                     $itemSource,
                     $shareType,
                     $shareWith,
                     ($permissions & $maxpermissions)
                  );
               }

               if(!empty($expiration)) {  
                  OCP\Share::setExpirationDate($itemType, $itemSource, $expiration);
               }
               if($useToken) {
                  ResumeShare::setTokenSetting($useToken, $itemSource, $itemType, $shareWith);
               }

               // use a link with token regardless of sharing type 
               if(!isDevMode() && !empty($shareWith)) {
                  /* send mail */
                  require_once JPATH_SITE.'/components/com_jobmail/models/email.php';
                  $mailer = new JobmailModelEmail();
                  $config = PFactory::getConfig();
                  $supportmail = $config->get('mailfrom','');
                  $displayName = OCP\User::getDisplayName();

                  $mailer->setTemplate('hrsimple');
                  $receivers = array();
                  for($i=0;$i<count($emailArr);$i++) {
                     $token = ResumeShare::getToken($itemSource, $itemType, $emailArr[$i]);
                     $link = null;
                     $loginlink = OC_Helper::linkToRoute('company_login');
                     if($token) {
                        $link = OC_Helper::linkTo('', 'public.php') .
                        '?service='.$itemType.
                        '&t='.$token;
                     }
                     if($shareType === OCP\Share::SHARE_TYPE_GROUP) {
                        $users = $model->usersInGroup($emailArr[$i]); 
                        foreach($users as $user) {
                           array_push($receivers, $user->uid); 
                        }
                     }
                     else if(JMailHelper::isEmailAddress($emailArr[$i])) {
                        array_push($receivers,$emailArr[$i]);
                     }
                  }

                  $config = PFactory::getConfig(); 
                  $cuser = PFactory::getUser();
                  $receivers = array_values(array_unique(array_diff($receivers, $sharedlist)));
                  foreach($receivers as $receiver) {
                     $plink = $link ? $link . '&w='. OC_Util::sanitizeHTML($receiver) : $loginlink; 
                     $plink = OC_Request::serverProtocol(). '://' . OC_Request::serverHost() .$plink;
                     if(!empty($shareWords)){
                        $words = '<p class="p2"><b>'.$shareWords.'</b></p>';
                     }else{
                     	$words = '';
                     }
                     
                     $rModel = new PResumesModelResume();
                     $resumeInfo = $rModel->getResumeJobDetail($itemSource);
                     
                     $body = '<p class="p1"><b>您好！</b></p>
                              <p class="p3"><b>'.$displayName.'</b>给您分享了一份简历('. $resumeInfo->name .($resumeInfo->system == 1 ? '' : ' 申请的 ' . $resumeInfo->job_title . '职位') . ')，请及时查看：</p>
                              <p>
                              '.$words.'
                              <p class="p3"><a target="_blank" href="'.$plink.'">'.$plink.'</a></p>' ;

                     $receiver = (isDevMode() || isTestMode() || $cuser->testuser) ? $config->get('employeremail', '') : $receiver;

                     $mailer->setVariables(array(
                        'recipient'=>$receiver,
                        'fromName'=>'枇杷派云招聘',
                        'subject'=>'简历分享：'.($resumeInfo->system == 1 ? '' : $resumeInfo->job_title).$resumeInfo->name,
                        'supportmail'=>$supportmail,
                        'hrurl'=>'http://'.OC_Request::serverHost(),
                        'body'=>$body
                        )
                     );

                     $mailer->send();
                  }
               }

               // Event Driven Cache/Object Caching - clear any cache related to affected tables 
               CacheHelper::triggerRemove(OC_User::getUser(), array('*PREFIX*share', '*PREFIX*share-'.$itemSource));

               if (is_array($notsharedlist)) {
                  OC_JSON::success(array('data' => array('token' => $token,'sharelist' => $notsharedlist)));
               } else if (is_string($token)) {
                 OC_JSON::success(array('data' => array('token' => $token)));
               } else {
                  OC_JSON::success();
               }
            } catch (Exception $exception) {
               OC_JSON::error(array('data' => array('message' => $exception->getMessage())));
            }
         }
         break;
      case 'unshare':
         if (isset($_POST['shareType']) && isset($_POST['shareWith'])) {
            if ((int)$_POST['shareType'] === OCP\Share::SHARE_TYPE_LINK && $_POST['shareWith'] == '') {
               $shareWith = null;
            } else {
               $shareWith = $_POST['shareWith'];
            }
            if ((int)$_POST['shareType'] === OCP\Share::SHARE_TYPE_EMAIL) {
               $model = new PCompanyModelSubAccounts;
               /* share_type_email is share type link */
               $_POST['shareType'] = OCP\Share::SHARE_TYPE_LINK; 
            }
            // check permission 
            $maxpermissions = ResumeShare::getMaxPermissions(intval($_POST['itemSource'])); 
            if(!($maxpermissions & OCP\PERMISSION_SHARE)) {
               OC_JSON::error(array('data' => array('message' => "您无权访问该资源")));
               exit;
            }

            $return = OCP\Share::unshare($_POST['itemType'], $_POST['itemSource'], $_POST['shareType'], $shareWith);

            // Event Driven Cache/Object Caching - clear any cache related to affected tables 
            CacheHelper::triggerRemove(OC_User::getUser(), array('*PREFIX*share', '*PREFIX*share-'.intval($_POST['itemSource'])));

            ($return) ? OC_JSON::success() : OC_JSON::error();
         }
         break;
      case 'setPermissions':
         if (isset($_POST['shareType']) && isset($_POST['shareWith']) && isset($_POST['permissions'])) {
            $permissions  = ResumeShare::pickPermissions(JRequest::getInt('permissions', 0));

            // check permission 
            $maxpermissions = ResumeShare::getMaxPermissions(intval($_POST['itemSource'])); 
            if(!($maxpermissions & OCP\PERMISSION_SHARE)) {
               OC_JSON::error(array('data' => array('message' => "您无权访问该资源")));
               exit;
            }

            $return = OCP\Share::setPermissions(
               $_POST['itemType'],
               $_POST['itemSource'],
               $_POST['shareType'],
               $_POST['shareWith'],
               ($permissions & $maxpermissions)
            );

            // Event Driven Cache/Object Caching - clear any cache related to affected tables 
            CacheHelper::triggerRemove(OC_User::getUser(), array('*PREFIX*share', '*PREFIX*share-'.intval($_POST['itemSource'])));

            ($return) ? OC_JSON::success() : OC_JSON::error();
         }
         break;
      case 'setExpirationDate':
         if (isset($_POST['date'])) {
         	$date = PFactory::getDate($_POST['date']);
         	$_POST['date'] = $date->add(new DateInterval('P1D'))->format("Y-m-d H:i:s");

            // check permission 
            $maxpermissions = ResumeShare::getMaxPermissions(intval($_POST['itemSource'])); 
            if(!($maxpermissions & OCP\PERMISSION_SHARE)) {
               OC_JSON::error(array('data' => array('message' => "您无权访问该资源")));
               exit;
            }

            $return = OCP\Share::setExpirationDate($_POST['itemType'], $_POST['itemSource'], $_POST['date']);

            // Event Driven Cache/Object Caching - clear any cache related to affected tables 
            CacheHelper::triggerRemove(OC_User::getUser(), array('*PREFIX*share', '*PREFIX*share-'.intval($_POST['itemSource'])));

            ($return) ? OC_JSON::success() : OC_JSON::error();
         }
         break;
      case 'setSetting': 
         $itemSource = JRequest::getInt('itemSource', '');
         $itemType = JRequest::getString('itemType', '');
         $useToken = JRequest::getInt('setting', 0); 

         // check permission 
         $maxpermissions = ResumeShare::getMaxPermissions($itemSource); 
         if(!($maxpermissions & OCP\PERMISSION_SHARE)) {
            OC_JSON::error(array('data' => array('message' => "您无权访问该资源")));
            exit;
         }

         $return = ResumeShare::setTokenSetting($useToken, $itemSource, $itemType); 

         // Event Driven Cache/Object Caching - clear any cache related to affected tables 
         CacheHelper::triggerRemove(OC_User::getUser(), array('*PREFIX*share-'.$itemSource));

         $return ? OC_JSON::success() : OC_JSON::error();
         break; 
   }
} else if (isset($_GET['fetch'])) {
   switch ($_GET['fetch']) {
      case 'getItemsSharedStatuses':
         if (isset($_GET['itemType'])) {
            $return = OCP\Share::getItemsShared($_GET['itemType'], OCP\Share::FORMAT_STATUSES);
            is_array($return) ? OC_JSON::success(array('data' => $return)) : OC_JSON::error();
         }
         break;
      case 'getItem':
         if (isset($_GET['itemType'])
            && isset($_GET['itemSource'])
            && isset($_GET['checkReshare'])
            && isset($_GET['checkShares'])) {
            if ($_GET['checkReshare'] == 'true') {
               $reshare = OCP\Share::getItemSharedWithBySource(
                  $_GET['itemType'],
                  $_GET['itemSource'],
                  OCP\Share::FORMAT_NONE,
                  null,
                  true
               );
            } else {
               $reshare = false;
            }
            if ($_GET['checkShares'] == 'true') {
               $shares = OCP\Share::getItemShared(
                  $_GET['itemType'],
                  $_GET['itemSource'],
                  OCP\Share::FORMAT_NONE,
                  null,
                  true
               );

               // if $shares is empty, add a null share item to avoid a second ajax POST request 
               if(empty($shares)) {
                  try {
                     $token = OCP\Share::shareItem(
                              $_GET['itemType'],
                              $_GET['itemSource'],
                              OCP\Share::SHARE_TYPE_LINK,
                              null,
                              OCP\PERMISSION_READ);
                     if($token) {
                        CacheHelper::triggerRemove(OC_User::getUser(), array('*PREFIX*share-'.$_GET['itemSource']));
                        $shares = array(); 
                        $shares[1] = array('id'=>0, 
                                           'item_type'=>'resumes', 
                                           'item_source'=>$_GET['itemSource'], 
                                           'share_type'=>OCP\Share::SHARE_TYPE_LINK,
                                           'share_with'=>null,
                                           'permissions'=>OCP\PERMISSION_READ,
                                           'stime'=>time(),
                                           'expiration'=>null,
                                           'token'=>$token);
                     
                     }
                  } catch (Exception $exception) { }
               }

            } else {
               $shares = false;
            }

            OC_JSON::success(array('data' => array('reshare' => $reshare, 'shares' => $shares)));
         }
         break;
      case 'getpositionemail':
         if (isset($_GET['itemType']) && isset($_GET['itemSource'])){
            $emails = ResumeShare::getPositionEmailBySource($_GET['itemSource']);
         }else{
            $emails = false;
         }
         OC_JSON::success(array('data' => array('emails' => $emails)));
         break;
      case 'getShareWith':
         if (isset($_GET['search'])) {
            $sharePolicy = OC_Appconfig::getValue('core', 'shareapi_share_policy', 'global');
            $shareWith = array();

            $model = new PCompanyModelSubAccounts; 
            if ($sharePolicy == 'groups_only' && !PFactory::isAdminUser()) {
               $groups = $model->searchUserGroups(OC_User::getUser(), $_GET['search']); 
            } else {
               $groups = $model->searchGroups($_GET['search']);
               $users = $model->searchUsers($_GET['search']);
            }

            foreach ($users as $user) {
               if ((!isset($_GET['itemShares'])
                  || !is_array($_GET['itemShares'][OCP\Share::SHARE_TYPE_USER])
                  || !in_array($user->uid, $_GET['itemShares'][OCP\Share::SHARE_TYPE_USER]))
                     && $user->uid != OC_User::getUser()) {
                     $shareWith[] = array(
                        'label' => $user->displayname,
                        'value' => array(
                           'shareType' => OCP\Share::SHARE_TYPE_USER,
                           'shareWith' => $user->uid)
                     );
               }
            }

            foreach ($groups as $group) {
               if ((!isset($_GET['itemShares'])
                  || !isset($_GET['itemShares'][OCP\Share::SHARE_TYPE_GROUP])
                  || !is_array($_GET['itemShares'][OCP\Share::SHARE_TYPE_GROUP])
                  || !in_array($group, $_GET['itemShares'][OCP\Share::SHARE_TYPE_GROUP]))) {
                     $shareWith[] = array(
                        'label' => $group->groupname.' (分组)',
                        'value' => array(
                           'shareType' => OCP\Share::SHARE_TYPE_GROUP,
                           'shareWith' => $group->groupname
                     )
                  );
               }
            } 
            OC_JSON::success(array('data' => $shareWith));
         }
         break;
   }
}
